package com.leyou.search.service.impl;

import com.leyou.common.dto.PageDTO;
import com.leyou.item.clients.ItemClient;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.search.entity.Goods;
import com.leyou.search.repository.GoodsRepository;
import com.leyou.search.service.IndexService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class IndexServiceImpl implements IndexService {
    @Autowired
    private ItemClient itemClient;

    @Autowired
    private GoodsRepository goodsRepository;

    //1,链接，goods，是spu的变形
    //需要访问item服务获取spu

    @Override
    public void loadData() {
        deleteAndCreateIndexes();


        //对商品数据spu进行分页查询
        int page = 1;
        while (true) {
            PageDTO<SpuDTO> spuDTOPageDTO =
                    this.itemClient.pageQuery(page, 50, true, null, null, null);

            //根本没有数据
            if (0 == spuDTOPageDTO.getTotalPage()) {
                break;
            }

            //biz  把查询到的spuDTO的集合转换为goods的集合
            List<Goods> goodsList = spuDTOPageDTO.getItems().stream().map(this::buildGoods).collect(Collectors.toList());


            //批量保存goods到索引库
            this.goodsRepository.saveAll(goodsList);

            page++;

            if (page > spuDTOPageDTO.getTotalPage()) {
                break;
            }
        }
    }

    private void deleteAndCreateIndexes() {
        //删除索引库，创建索引库

        try {
            this.goodsRepository.deleteIndex();
        } catch (Exception e) {
        }

        //建库
        this.goodsRepository.createIndex("{\n" +
                "  \"settings\": {\n" +
                "    \"analysis\": {\n" +
                "      \"analyzer\": {\n" +
                "        \"my_pinyin\": {\n" +
                "          \"tokenizer\": \"ik_smart\",\n" +
                "          \"filter\": [\n" +
                "            \"py\"\n" +
                "          ]\n" +
                "        }\n" +
                "      },\n" +
                "      \"filter\": {\n" +
                "        \"py\": {\n" +
                "\t\t  \"type\": \"pinyin\",\n" +
                "          \"keep_full_pinyin\": true,\n" +
                "          \"keep_joined_full_pinyin\": true,\n" +
                "          \"keep_original\": true,\n" +
                "          \"limit_first_letter_length\": 16,\n" +
                "          \"remove_duplicated_term\": true\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  },\n" +
                "  \"mappings\": {\n" +
                "    \"properties\": {\n" +
                "      \"id\": {\n" +
                "        \"type\": \"keyword\"\n" +
                "      },\n" +
                "      \"suggestion\": {\n" +
                "        \"type\": \"completion\",\n" +
                "        \"analyzer\": \"my_pinyin\",\n" +
                "        \"search_analyzer\": \"ik_smart\"\n" +
                "      },\n" +
                "      \"title\":{\n" +
                "        \"type\": \"text\",\n" +
                "        \"analyzer\": \"my_pinyin\",\n" +
                "        \"search_analyzer\": \"ik_smart\"\n" +
                "      },\n" +
                "      \"image\":{\n" +
                "        \"type\": \"keyword\",\n" +
                "        \"index\": false\n" +
                "      },\n" +
                "      \"updateTime\":{\n" +
                "        \"type\": \"date\"\n" +
                "      },\n" +
                "      \"specs\":{\n" +
                "        \"type\": \"nested\",\n" +
                "        \"properties\": {\n" +
                "          \"name\":{\"type\": \"keyword\" },\n" +
                "          \"value\":{\"type\": \"keyword\" }\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  }\n" +
                "}");
    }

    //把查询到的spuDTO转换为goods
    @Override
    public Goods buildGoods(SpuDTO spuDTO) {
        Goods goods = new Goods();

        BeanUtils.copyProperties(spuDTO, goods);


        //categoryId

        goods.setCategoryId(spuDTO.getCid3());


        //suggestion 候选值，主体名称，品牌+主体,品牌+分类，分类+品牌


        //侯选值的目的，就是满足搜索提示
        List<String> suggestList = new ArrayList<>();


        String goodsName = spuDTO.getName();
        String categoryName = spuDTO.getCategoryName().split("/")[2];
        String brandName = StringUtils.substringBefore(spuDTO.getBrandName(), "（");


        suggestList.add(goodsName);

        suggestList.add(goodsName.startsWith(brandName) ? brandName : brandName + goodsName);
        suggestList.add(brandName + categoryName);
        suggestList.add(categoryName + brandName);


        goods.setSuggestion(suggestList);


        String title = goodsName + " " + brandName + " " + categoryName;
        goods.setTitle(title);

        List<SkuDTO> skuDTOS = this.itemClient.listSkuBySpu(spuDTO.getId());

        Set<Long> prices = new HashSet<>();

        long sold = 0L;
        //取出所有sku 的价格,以及统计sold销量
        for (SkuDTO skuDTO : skuDTOS) {
            prices.add(skuDTO.getPrice());
            sold += skuDTO.getSold();
        }

        //prices
        goods.setPrices(prices);
        //sold
        goods.setSold(sold);


        //image
        //随便找一个sku取图片，要一个图片就可以了
        goods.setImage(StringUtils.substringBefore(skuDTOS.get(0).getImages(), ","));
        //updateTime
        goods.setUpdateTime(new Date());


        //specs 可搜索规格参数以及值


        //获取所有的可搜索规格参数,从其中取出参数名称作为map的key，参数的值作为map的value
        List<Map<String, Object>> specs = this.itemClient.listSpec(spuDTO.getId(), true)
                .stream()
                .map(specParamDTO -> {
                    Map<String, Object> resultMap = new HashMap<>();
                    resultMap.put("key", specParamDTO.getName());

                    //value如果是数值的，有区间，选择区间
                    resultMap.put("value", chooseSegment(specParamDTO));
                    return resultMap;
                }).collect(Collectors.toList());


        goods.setSpecs(specs);

        return goods;
    }

    @Override
    public void crateIndex(Long id) {
        //根据spuId做查询
        PageDTO<SpuDTO> spuDTOPageDTO =
                this.itemClient.pageQuery(1, 1, true, null, null, id);

        //如果查询到了
        if (1 == spuDTOPageDTO.getTotal()) {
            //把查询到的spuDTO取出转换为goods并保存
            SpuDTO spuDTO = spuDTOPageDTO.getItems().get(0);
            this.goodsRepository.save(buildGoods(spuDTO));
        }
    }

    @Override
    public void deleteIndex(Long id) {
        this.goodsRepository.deleteById(id);
    }

    private Object chooseSegment(SpecParamDTO p) {
        Object value = p.getValue();
        if (value == null || StringUtils.isBlank(value.toString())) {
            return "其它";
        }
        if (!p.getNumeric() || StringUtils.isBlank(p.getSegments()) || value instanceof Collection) {
            return value;
        }
        double val = parseDouble(value.toString());
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = parseDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = parseDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }

    private double parseDouble(String str) {
        try {
            return Double.parseDouble(str);
        } catch (Exception e) {
            return 0;
        }
    }
}
